<template>
  <div class="task-detail">
    <van-sticky>
      <div class="select-box">
        <component
          :is="searchTemp"
          placeholder="搜索"
          v-model="filterData.text"
          @onSearch="onRefresh"
        />
        <van-icon
          name="filter-o"
          @click="echoData.visible = true"
        />
      </div>
    </van-sticky>
    <van-pull-refresh v-model="state.refresh" @refresh="onRefresh">
      <div class="total" v-if="state.total">{{ `共有${state.total}条记录` }}</div>
      <van-list
        :loading="state.loading"
        :finished="state.finished"
        :finished-text="state.list?.length !== 0 ? '———— 已经到底了哦 ————' : '' "
        @load="getList"
      >
        <div class="lists" v-if="state.list?.length">
          <component
            :is="buildingItem"
            v-for="item in state.list"
            :key="item.id"
            :details="item"
            @click="toDetail(item)"
          />
        </div>
        <component
          :is="empty"
          v-if="!state.list?.length && !state.loading"
        />
      </van-list>
    </van-pull-refresh>

    <van-popup
      position="bottom"
      v-model:show="echoData.visible"
      round
      :close-on-click-overlay="false"
    >
      <div class="filter">
        <p @click="onFilterCancel">取消</p>
        <p>筛选</p>
        <p @click="onFilterConfirm">确认</p>
      </div>
      <van-form>
        <van-field
          label="核验状态"
          readonly
        >
          <template #input>
            <van-radio-group v-model="filterData.hyzt" direction="horizontal">
              <van-radio
                v-for="item in echoData.sortEnum"
                :name="item.value"
                :key="item.value"
              >
                {{ item.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          label="行政区"
          v-model="echoData.countyName"
          placeholder="请选择"
          readonly
          is-link
          @click="changeRegion('county')"
        />
        <van-field
          v-if="filterData.xzqdm"
          label="镇街"
          v-model="echoData.townshipName"
          placeholder="请选择"
          readonly
          is-link
          @click="changeRegion('township')"
        />
        <van-field
          v-if="filterData.towndm"
          label="村"
          v-model="echoData.villageName"
          placeholder="请选择"
          readonly
          is-link
          @click="changeRegion('village')"
        />
      </van-form>
    </van-popup>
    
    <van-popup v-model:show="echoData.regionVisible" position="bottom" round>
      <van-picker
        :columns="echoData[echoData.regionType]"
        @confirm="onConfirm"
        @cancel="echoData.regionVisible = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { reactive, nextTick, onMounted } from 'vue'
import empty from '@/components/empty'
import { getRegion, getTaskDetail } from '@/service/village'
import buildingItem from './components/buildingItem.vue'
import searchTemp from '@/components/searchTemp.vue'
import { useRouter, useRoute } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useLoginStore } from '@/store'

const router = useRouter()
const route = useRoute()
const loginStore = useLoginStore()
const { loginInfo } = storeToRefs(loginStore)

const filterData = reactive({
  text: '',
  hyzt: '-1',
  xzqdm: '',
  towndm: '',
  villagedm: '',
})

const echoData = reactive({
  visible: false,
  regionVisible: false,
  regionType: 'county',
  countyName: '',
  county: [],
  townshipName: '',
  township: [],
  villageName: '',
  village: [],
  sortEnum: [
    { value: '-1', text: '全部' },
    { value: '0', text: '未核验' },
    { value: '1', text: '已核验' },
  ],
})
const state = reactive({
  loading: false,
  finished: false,
  total: 0,
  page: 1,
  pageSize: 10,
  list: []
})

const onRefresh = () => {
  state.list = []
  state.page = 1
  state.refresh = false
  state.loading = false
  state.finished = true
  nextTick(() => {
    state.finished = false
  })
}

const getList = async () => {
  const params = {
    taskid: route.query.id,
    pageindex: state.page -  1,
    limit: state.pageSize,
    ...filterData,
    hyzt: +filterData.hyzt,
  }
  try {
    state.loading = true
    const result = await getTaskDetail(params)
    state.loading = false
    state.list = [...state.list, ...result.data.items]
    state.total = result.data.total
    if (state.page * state.pageSize >= state.total) {
      state.finished = true
    }
    state.page++
  } catch (err) {
    state.loading = false
    state.finished = true
  }
}

const changeRegion = type => {
  const roleEnum = {
    2: ['county', 'township', 'village'],
    3: ['township', 'village'],
    4: ['village'],
  }
  if (roleEnum[loginInfo.value.roletype].includes(type)) {
    echoData.regionType = type
    nextTick(() => {
      echoData.regionVisible = true
    })
  }
}

const onConfirm = val => {
  echoData.regionVisible = false
  if (echoData.regionType === 'county') {
    echoData.countyName = val?.regionName
    filterData.xzqdm = val?.regionCode
    echoData.townshipName = ''
    filterData.towndm = ''
    echoData.villageName = ''
    filterData.villagedm = ''
    getRegionData(val?.regionCode, 'township')
  } else if (echoData.regionType === 'township') {
    echoData.townshipName = val?.regionName
    filterData.towndm = val?.regionCode
    echoData.villageName = ''
    filterData.villagedm = ''
    getRegionData(val?.regionCode, 'village')
  } else if (echoData.regionType === 'village') {
    echoData.villageName = val?.regionName
    filterData.villagedm = val?.regionCode
  }
}

const onFilterConfirm = () => {
  echoData.visible = false
  onRefresh()
}

const onFilterCancel = () => {
  echoData.visible = false
  initFiterData()
  onRefresh()
}

const initFiterData = () => {
  filterData.text = ''
  filterData.hyzt = '-1'
  filterData.xzqdm = loginInfo.value?.xzqdm
  filterData.towndm = loginInfo.value?.towndm
  filterData.villagedm = loginInfo.value?.villagedm
  echoData.countyName = loginInfo.value?.xzq
  echoData.townshipName = loginInfo.value?.town
  echoData.villageName = loginInfo.value?.village
}


const toDetail = record => {
  beforeLeave()
  router.push({
    name: 'verification-village-collect',
    query: {
      id: record?.fwbh,
      fwbh: record?.fwbh,
      iscj: 1,
      detailId: record.id,
    }
  })
}

const beforeLeave = () => {
  sessionStorage.setItem('filterData', JSON.stringify(filterData))
  sessionStorage.setItem('echoData', JSON.stringify(echoData))
  sessionStorage.setItem('hasQuery', 1)
}

const initQuery = () => {
  const filter = JSON.parse(sessionStorage.getItem('filterData'))
  Object.keys(filter)?.forEach(key => {
    filterData[key] = filter[key]
  })
  const echo = JSON.parse(sessionStorage.getItem('echoData'))
  Object.keys(echo)?.forEach(key => {
    echoData[key] = echo[key]
  })
  sessionStorage.removeItem('filterData')
  sessionStorage.removeItem('echoData')
  sessionStorage.removeItem('hasQuery')
}


const getRegionData = async (id, type) => {
  const result = await getRegion({
    parentid: id
  })
  if (result?.succ) {
    echoData[type] = result?.data?.map(item => {
      return {
        text: item.regionName,
        ...item
      }
    })
  }
}

onMounted(() => {
  if (sessionStorage.getItem('hasQuery')) {
    initQuery()
  } else {
    initFiterData()
    if ([2, 3, 4].includes(loginInfo.value?.roletype)) {
      getRegionData(
        loginInfo.value?.regionCode,
        loginInfo.value?.roletype === 2 ? 'county'
          : loginInfo.value?.roletype === 3 ? 'township'
            : loginInfo.value?.roletype === 4 ? 'village'
              : ''
      )
    }
  }
  
})
</script>

<style scoped lang="less">
.task-detail {
  .total {
    height: 82px;
    line-height: 82px;
    text-align: center;
    color: #696969;
  }
  .filter {
    display: flex;
    padding: 32px;
    p {
      &:nth-of-type(1) {
        color: var(--time-color);
      }
      &:nth-of-type(2) {
        flex: 1;
        font-size: 32px;
        text-align: center;
      }
      &:nth-of-type(3) {
        color: var(--van-primary-color);
      }
    }
  }
  .select-box {
    display: flex;
    align-items: center;
    background: #fff;
    padding-right: 32px;
    i {
      font-size: 36px;
      color: var(--van-primary-color);
    }
  }
  :deep(.van-form) {
    .van-cell {
      .van-field__label {
        width: 160px;
      }
      .van-cell__value {
        .van-field__body {
          input {
            border: 0;
          }
        }
      }
    }
  }
}
</style>
